关于gcc中string的cow机制

梗概

已知 C++ 11禁止使用COW,本文进行验证。

测试代码

#include 
#include 
#include

int main() {
    std::string origin("cow\n");
    std::string copy( origin);

    printf(origin.c_str());
    printf(copy.c_str());
    printf("origin\taddress is %x\n",(int64_t)origin.c_str());
    printf("copy\taddress is %x\n",(int64_t)copy.c_str());
    copy[0] = 'w';
    printf(origin.c_str());
    printf(copy.c_str());
    printf("origin\taddress is %x\n",(int64_t)origin.c_str());
    printf("copy\taddress is %x\n",(int64_t)copy.c_str());
    return 0;
}

使用gcc 6.3.0测试

$ g++ -o cow cow.cpp --std=c++98

$ ./cow
cow
cow
origin  address is 8c69cc40
copy    address is 8c69cc20
cow
wow
origin  address is 8c69cc40
copy    address is 8c69cc20

$ g++ -o cow cow.cpp --std=c++11
$ ./cow
cow
cow
origin  address is 28240270
copy    address is 28240250
cow
wow
origin  address is 28240270
copy    address is 28240250

使用gcc 4.8.5测试

$ g++ -o cow cow.cpp --std=c++98
$ ./cow
cow
cow
origin  address is aa9028
copy    address is aa9028
cow
wow
origin  address is aa9028
copy    address is aa9058

$ g++ -o cow cow.cpp --std=c++11
$ ./cow
cow
cow
origin  address is 23a0028
copy    address is 23a0028
cow
wow
origin  address is 23a0028
copy    address is 23a0058

结论

从gcc的实际的实现看,cow 并非是c++11之后禁止的,而是从gcc的某个版本开始禁止cow机制,与c++11无必然关系。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注