C++ 修改临时文件是否不正确?
在C++98/03/11中,以下代码有效:C++ 修改临时文件是否不正确?,c++,C++,在C++98/03/11中,以下代码有效: std::string meow() { return "meow"; } int main() { meow().append("purr"); return 0; } 由于临时模具位于分号处,因此这应该是安全的,对吗?这并不错误,在某些情况下这样做是有用的 假设我有一个包含大量数据的向量,我想清除数据和内存 { std::vector< int >().swap( myVec ); } 那里的实现修改一个临
std::string meow() { return "meow"; }
int main()
{
meow().append("purr");
return 0;
}
由于临时模具位于分号处,因此这应该是安全的,对吗?这并不错误,在某些情况下这样做是有用的 假设我有一个包含大量数据的向量,我想清除数据和内存
{
std::vector< int >().swap( myVec );
}
那里的实现修改一个临时值,然后按值返回它(C++11中的r值引用,C++03中的按值)
显然,对于r值引用,您有更多的示例,例如在您的案例中,您可以返回
meow()。append(“purr”)
这是合法的,而且很有用:
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
};
class-Foo{
int*数据;
公众:
Foo(){data=new int[100];}
Foo(const Foo&other){//copy ctor
if(其他.data!=nullptr){
data=new int[100];//创建一个新数组
对于(unsigned i=0;我知道这只是一个例子,但万一有人不知道..在C++11中,你可以使用shrink\u-to-fit
@NeilKirkshrink\u-to-fit
是非约束性的。不,但它会提示编译器。我们相信编译器会在需要时进行其他优化,为什么不使用这个呢?@NeilKirk这不是真正的编译器问题;它是一个库罕见的问题。如果你想100%确保内存被释放,那么交换仍然是一条路要走。如果你想防止这种行为,你可以返回一个const std::string
。看起来很有趣。请详细说明!不。删除等于nullptr
的指针没有任何作用:)@TobiMcNamobi你知道我还能改进什么吗?
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
};