小编Ste*_*ong的帖子

C++ destructor called before lifetime of scope

I have a question about triggering a destructor for an object prematurely. I have an dynamically allocated array of pointers to dynamically allocated Word objects. The name of the array is words_. words_ is a class attribute of another class called Dictionary.

In my Dictionary class, I have a function where I access each Word object and call a member function of the Word class.

The below code triggers the destructor prematurely:

Word *curr_word_ptr = words_[idx]; // This line is …
Run Code Online (Sandbox Code Playgroud)

c++ stack memory-leaks memory-management heap-memory

1
推荐指数
1
解决办法
90
查看次数

strtok_r() 和 strsep() 的 C 字符串替代品不会修改原始字符串指针?

我查看了 2 个 C 字符串函数 strtok_r() 和 strsep(),并注意到这两个函数都会修改传入的原始字符串的位置。

是否还有其他不修改传入的原始字符串的 C 字符串函数?

在我的应用程序中,原始字符串是动态分配的,因此我希望在解析完成后释放原始字符串。

strtok_r() 的示例

int main(){
    char * str = strdup("Tutorial and example");
    char* token;
    char* rest = str;
    
    printf("%s\n", rest);
    while ((token = strtok_r(rest, " ", &rest)))
        printf("%s\n", token);
    printf("\n%s\n",str);
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

输出

Tutorial and example                                                                                                                                                        
Tutorial                                                                                                                                                                    
and                                                                                                                                                                         
example                                                                                                                                                                     
                                                                                                                                                                            
                                                                                                                                                                            
                                                                                                                                                                            
Tutorial                                                                                                                                                                          
Run Code Online (Sandbox Code Playgroud)

在最后一行,我希望 str 指向未修改的 cstring“教程和示例”。

strsep() 也会出现类似的输出。

int main(){
    char * str = strdup("Tutorial and example");
    char* token;
    char* rest = str;

    printf("%s\n", rest); 
    while ((token = strsep(&rest, " "))) …
Run Code Online (Sandbox Code Playgroud)

c split c-strings strtok strsep

1
推荐指数
1
解决办法
1149
查看次数