2014-10-06 66 views
4

在C++ 98/03/11中的下面的代码是有效的:修改临时文件不正确吗?

std::string meow() { return "meow"; } 

int main() 
{ 
    meow().append("purr"); 
    return 0; 
} 

由于在分号临时模具,这应该是安全的吗?

+0

如果你想阻止这种行为,你可以实际上返回一个'const std :: string'。 – pmr 2014-10-06 11:15:02

回答

4

这并不正确,在某些情况下这样做很有用。

假设我有很多数据的载体,我要清除的数据和存储..

{ 
    std::vector<int>().swap(myVec); 
} 

将清除内存一定的。 myVec.clear()可能只改变逻辑大小回0

正如我在以前的问题表明你可以使用它像这样:

class Foo 
{ 
    public: 
     Foo& operator+=(Foo const&); // implement 
     Foo operator+(Foo const& rhs) const 
     { 
      return Foo(*this) += rhs; 
     } 
}; 

有执行修改临时然后通过返回的值是(R C++ 11中的值参考,按C++ 03中的值)。

与R值引用

很明显,你有更多的例子像你的情况,你可以返回meow().append("purr")

+0

我知道这只是一个例子,但如果有人不知道..在C++ 11中,你可以使用'shrink_to_fit' – 2014-10-06 11:13:00

+0

@NeilKirk'shrink_to_fit'不具有约束力。 – 2014-10-06 11:29:09

+0

不,但它暗示编译器。我们相信编译器会在需要时进行其他优化,为什么不这样呢? – 2014-10-06 11:34:34

1

这是合法的,并且有用:

class Foo{ 
    int *data; 
public: 
    Foo(){data=new int[100];} 
    Foo(const Foo& other){ //copy ctor 
     if(other.data!=nullptr){ 
      data=new int[100]; //make a new array 
      for(unsigned i=0; i<100; ++i) // 
       data[i]=other.data[i]; //fill it using content of other 
     } 
    } 
    Foo(Foo&& other){ //move ctor 
     data=other.data; /* obvioulsly grab the other's pointer :) 
          * other is a temporary, so we don't have to 
          * allocate new array and copy other's content, 
          * because other is going to disappear soon. 
          */ 
     other.data=nullptr; /* Without this line, other and *this 
          * have the same pointer! 
          * When *this or other gets destroyed, 
          * it frees the data; second object 
          * doesn't know about the deletion, 
          * and may still want to use the data, 
          * causing undefined behavior by using fryed memory. 
          */ 
    } 
    ~Foo(){delete[] data;} //frees data 
}; 
+0

看起来很有趣。请详细说明! – TobiMcNamobi 2014-10-06 11:24:13

+0

您删除了一个无效指针。 – 2014-10-06 11:35:00

+1

没有。删除等于'nullptr'的指针什么也不做:) – GingerPlusPlus 2014-10-06 11:37:10